package com.gpj.learn.rabbitmq.helloworld;

import com.gpj.learn.rabbitmq.common.CommonConstants;
import com.gpj.learn.rabbitmq.common.DateTimeUtil;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import lombok.extern.slf4j.Slf4j;

/**
 * @className Producer
 * @description
 *   TODO
 * @author GPJ
 * @date 2021/5/30 11:39
 * @version 1.0
 **/
@Slf4j
public class Producer {
	public static void main(String[] args) throws IOException, TimeoutException {
		log.info("------------- 开始发送消息 -------------");
		// 获取TCP长连接
		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost(CommonConstants.RABBITMQ_HOST);
		factory.setPort(CommonConstants.RABBITMQ_PORT);
		factory.setUsername(CommonConstants.RABBITMQ_USER);
		factory.setPassword(CommonConstants.RABBITMQ_PASSWORD);
		factory.setVirtualHost(CommonConstants.RABBITMQ_VIRTUALHOST);

		Connection connection = factory.newConnection();

		// 获取通道
		Channel channel = connection.createChannel();

		// 创建队列
		channel.queueDeclare(
				CommonConstants.RABBITMQ_QUEUE_HELLOWORLD, // 队列名称
				false, // 是否持久化,false-不持久化
				false, // 是否队列私有化,false-非私有化,全部消费者均可消费;true-私有化,第一次拥有该队列的消费者才可以使用
				false, // 是否自动删除,false-连接停止之后不自动删除该队列
				null); // 额外参数

		// 发送消息
		String message = "hello world" + DateTimeUtil.format(DateTimeUtil.nowDateTime());

		channel.basicPublish(
				"", // 指定交换机
				CommonConstants.RABBITMQ_QUEUE_HELLOWORLD, // 队列名
				null, // 额外设置
				message.getBytes()); // 消息内容


		channel.close();
		connection.close();
		log.info("------------- 消息发送完成 -------------");
	}
}
